<template>
  <div>
    <a-drawer title="补货" placement="right" :closable="true" :visible="visible" @close="onClose" :zIndex="10" :width="goodsVisible ? '90%' : 800" :destroyOnClose="true" :maskClosable="false">
      <!-- <div class="title" style="margin-top: 54px">补货记录</div>
    <replenishRecord :boxId="boxId" @getRecordList="getRecordList" :updateRecord="updateRecord"></replenishRecord> -->
      <div style="display:flex;">
        <section :style="{ width: goodsVisible ? '50%' : '100%' }" class="left">
          <div class="section" style="padding-right:12px;padding-bottom:24px;">
            <section style="margin-top: 16px">
              <a-form>
                <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="补货原因：" required>
                  <a-select v-model="reason" placeholder="请选择">
                    <a-select-option :value="item.key" v-for="(item, index) in reasonList" :key="index">{{ item.value }}</a-select-option>
                  </a-select>
                </a-form-item>
                <a-form-item :labelCol="labelCol" :wrapperCol="{ xs: { span: 20 }, sm: { span: 20 } }" label="客户地址：" required>
                  {{ logistic.name }}<a-divider type="vertical" />{{ logistic.phone }}<a-divider type="vertical" />{{ logistic.province }} {{ logistic.city }} {{ logistic.district }}
                  {{ logistic.address }} <a-button type="link" @click="changeAddress">更换地址</a-button>
                </a-form-item>
                <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="补货商品：" required>
                  <a-button type="primary" @click="goodsVisible = true" v-show="!goodsVisible">添加商品</a-button>
                  <a-button type="danger" @click="goodsVisible = false" v-show="goodsVisible">关闭商品库</a-button>
                </a-form-item>
              </a-form>
            </section>
            <section style="margin-bottom: 24px">
              <GoodsTable :tableData="tableData" :tableType="'replenish'" @updateData="updateData"></GoodsTable>
            </section>

            <div class="btn-box">
              <a-button style="margin-right: 20px;" @click="onClose">取消</a-button>
              <a-button type="primary" @click="handleSubmit" :loading="iconLoading" style="margin-right: 20px;">提交补货单</a-button>
              <a-checkbox v-model="virtual" :disabled="virtualDisabled">虚拟发货</a-checkbox>
            </div>
            <a-divider style="margin-bottom: 32px" />
            <section style="margin-top:32px;" class="order-section">
              <h3>搭盒</h3>
              <ProductsForReplen :data="filterGoods(goodsData)"></ProductsForReplen>
              <template v-if="goodsSupply && goodsSupply.length > 0">
                <section v-for="item in goodsSupply" :key="item.boxSupply.id">
                  <h3 class="supply-title">
                    <span>{{ '补货 ' + item.boxSupply.supplySn }} （原因：{{ item.boxSupply.supplyReason | supplyReason(reasonList) }}）</span>
                    <span>补货时间：{{ item.boxSupply.createTime }}</span>
                  </h3>
                  <ProductsForReplen :data="filterGoods(item.boxDetailsWithBLOBsList)"></ProductsForReplen>
                </section>
              </template>
              <template v-if="goodsChange && goodsChange.length > 0">
                <h3>换码</h3>
                <ProductsForReplen :data="filterGoods(goodsChange)"></ProductsForReplen>
              </template>
            </section>
          </div>
        </section>
        <section :style="{ width: '50%' }" v-if="goodsVisible" class="right">
          <div class="section" style="overflow-x:hidden;padding-top:24px;margin-left:24px">
            <Product :isEmit="true" @add="addProduct" :gender="-1" :unionId="unionId"></Product>
          </div>
        </section>
      </div>
      <!-- <a-drawer title="商品库" placement="right" :closable="true" :zIndex="11" :visible="goodsVisible" @close="onGoodsClose" :width="1100" :mask="false" :destroyOnClose="true">
        <Product :isEmit="true" @add="addProduct" :gender="-1" :unionId="unionId"></Product>
      </a-drawer> -->
    </a-drawer>
    <Address ref="address" :unionId="unionId" :defLogistic="logistic" @newAddress="newAddress" :title="'选择地址'"></Address>
  </div>
</template>
<script>
import Vue from 'vue'
import { USER_INFO } from '@/store/mutation-types'
import replenishRecord from './replenishRecord'
import Product from '@views/box/workbench/fashioner/module/product'
import GoodsTable from './goodsTable'
import ProductsForReplen from './productsForReplen'
import Address from '@/views/box/components/Address/AddressList'
import { boxSupplySave, boxSupplyCount, getProductInfo } from '@/api/box/order'
import { batchGetProductPromotionPrice } from '@/api/box/api'
import { initDictOptions, filterDictText } from '@/components/dict/JDictSelectUtil'
// import { getSupplyReason } from '@/views/box/util/global'
import globalData from '@/views/box/util/global'
export default {
  components: {
    replenishRecord,
    Product,
    GoodsTable,
    ProductsForReplen,
    Address
  },
  data() {
    return {
      visible: false,
      goodsVisible: false,
      boxId: '',
      labelCol: {
        xs: { span: 4 },
        sm: { span: 4 }
      },
      wrapperCol: {
        xs: { span: 8 },
        sm: { span: 8 }
      },
      reason: '',
      // 1.客户要求加单 2.问题款需更换 3.客户要换尺码 4.客户凑单付款 5.其他
      reasonList: [],
      tableData: [],
      supplyList: [],
      updateRecord: false,
      iconLoading: false,
      unionId: '',
      goodsData: [],
      goodsChange: [],
      goodsSupply: [],
      userInfo: Vue.ls.get(USER_INFO),
      supplyCount: 0,
      supplyGoodsCount: 0,
      boxDetail: {},
      logistic: {},
      virtual: false,
      virtualDisabled: false
    }
  },
  filters: {
    supplyReason(v, reasonList) {
      if (reasonList.length > 0) {
        let result = reasonList.filter(e => e.key == v)
        if (result.length > 0) {
          return result[0].value
        } else {
          return v
        }
      } else {
        return v
      }
    }
  },
  computed: {
    filterGoods(data) {
      return data => {
        let result = data.filter(e => e.status != 12 && e.status != 7)
        return result
      }
    }
  },
  watch: {
    tableData: {
      deep: true,
      immediate: true,
      handler(newValue) {
        let result = newValue.filter(e => e.eb)
        if (result.length > 0) {
          this.virtual = false
          this.virtualDisabled = true
        } else {
          this.virtualDisabled = false
        }
      }
    }
  },
  methods: {
    async show(id, unionId, boxDetail) {
      this.boxId = id
      this.unionId = unionId
      this.boxDetail = boxDetail
      this.logistic = {
        id: boxDetail.customerLogisticsId,
        customerLogisticsId: boxDetail.customerLogisticsId,
        name: boxDetail.name,
        phone: boxDetail.phone,
        province: boxDetail.province,
        city: boxDetail.city,
        district: boxDetail.district,
        address: boxDetail.address
      }
      this.tableData = []
      this.reason = ''
      this.updateRecord = false
      this.goodsVisible = false
      this.reasonList = globalData.boxSupplyReason
      await this.getSupplySetting()
      await this.fetchProductInfo()
      this.visible = true
    },
    getSupplySetting() {
      return initDictOptions('box_supply_setting').then(res => {
        if (res.success) {
          this.supplyCount = parseInt(res.result.filter(e => e.title == 'supplyCount')[0].value)
          this.supplyGoodsCount = parseInt(res.result.filter(e => e.title == 'supplyGoodsCount')[0].value)
        }
      })
    },
    onClose() {
      this.visible = false
      this.$emit('updateTable')
    },
    goodsShow() {
      this.goodsVisible = true
    },
    onGoodsClose() {
      this.goodsVisible = false
    },
    async addProduct(item) {
      const sku = item.skus.filter(sku => sku.id === item.currentSku.id)
      let productIds = [{ spuId: item.id }]
      let result = await this.getBatchPromotionPrice(productIds)
      let productFavorablePrice = null
      if (result.code == 0) {
        productFavorablePrice = result.data.productList[0].promotionPrice
      } else {
        this.$message.warning(result.msg)
      }
      const obj = {
        productColor: item.color_name,
        productColorNo: item.colorno,
        imgUrl: item.imgurl,
        productCode: item.name,
        productId: item.id,
        productName: item.value,
        productSize: sku[0].size_name,
        sizeNo: sku[0].sizeno,
        skuCode: sku[0].no,
        skuId: sku[0].id,
        productBrand: item.brand,
        productPrice: item.price,
        id: new Date().getTime() + '-' + sku[0].id,
        unionId: this.unionId,
        productFavorablePrice: productFavorablePrice,
        eb: sku[0].ifEb
      }
      this.tableData.push(obj)
      this.$message.success('已添加')
    },
    getBatchPromotionPrice(ids) {
      let params = {
        requestData: {
          unionId: this.unionId,
          productList: ids
        },
        user_id: this.userInfo.id
      }
      return batchGetProductPromotionPrice(params).then(res => {
        return res
      })
    },
    updateData(list) {
      this.tableData = list
    },
    getRecordList(list) {
      this.supplyList = list
    },
    // 提交补货单
    async handleSubmit() {
      let result = await this.getBoxSupplyCount()
      if (result.code == 0) {
        console.log(result.data)
        if (result.data.boxSupplyCount >= this.supplyCount) {
          this.$message.warning(`最多补货${this.supplyCount}次！`)
          return
        }
      } else {
        this.$message.warning(result.msg)
        return
      }
      if (this.reason == '') {
        this.$message.warning('请选择补货原因！')
        return
      }
      if (this.tableData.length == 0) {
        this.$message.warning('请选择补货商品！')
        return
      }
      if (this.tableData.length > this.supplyGoodsCount) {
        this.$message.warning(`单次最多补充${this.supplyGoodsCount}件商品！`)
        return
      }
      this.updateRecord = false
      this.iconLoading = true
      let skuIds = this.tableData.map(e => e.skuId)
      let params = {
        requestData: {
          boxId: this.boxId,
          skuIds: skuIds,
          supplyReason: this.reason,
          customerLogisticsId: this.logistic.id
        }
      }

      // 虚拟发货
      let hasEb = this.tableData.filter(e => e.eb)
      if (hasEb.length > 0) {
        this.virtual = false
        this.virtualDisabled = true
        params.requestData.ifVirDelivery = 0
      } else {
        params.requestData.ifVirDelivery = this.virtual ? 1 : 0
      }

      boxSupplySave(params).then(res => {
        if (res.code == 0) {
          this.$message.success('补货成功！')
          this.updateRecord = true
          this.iconLoading = false
          this.reason = ''
          this.tableData = []
          this.onClose()
        } else {
          this.iconLoading = false
          this.$message.warning(res.msg)
        }
      })
    },
    // 校验补货次数
    getBoxSupplyCount() {
      let params = {
        requestData: {
          boxId: this.boxId
        }
      }
      return boxSupplyCount(params).then(res => {
        return res
      })
    },
    fetchProductInfo() {
      let params = {
        requestData: {
          boxId: this.boxId
        }
      }
      return getProductInfo(params).then(res => {
        if (res.code == 0) {
          this.goodsData = res.data.createBoxList
          this.goodsChange = res.data.changeCodeList
          this.goodsSupply = res.data.supplyRespList
        }
      })
    },
    // 更换地址
    changeAddress() {
      this.$refs.address.show()
    },
    newAddress(record) {
      this.logistic = record
      this.logistic.name = record.contactName
      this.logistic.phone = record.contactPhone
      this.logistic.customerLogisticsId = record.id
    }
  }
}
</script>
<style lang="less" scoped>
.title {
  color: rgba(0, 0, 0, 0.85);
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 16px;
}
/deep/.ant-drawer-body {
  height: calc(100vh - 60px);
  box-sizing: border-box;
  padding: 0 24px;
  .btn-box {
    width: 100%;
    padding: 10px 16px;
    text-align: center;
  }
}
/deep/.ant-drawer-content-wrapper {
  transition: all 0.5s;
}
.supply-title {
  display: flex;
  justify-content: space-between;
  margin-top: 28px;
}
.section {
  height: calc(100vh - 60px);
  overflow-y: auto;
}
</style>

